<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="歌曲名称" prop="singName">
        <el-input v-model="queryParams.singName" placeholder="请输入歌曲名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:sing:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:sing:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:sing:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" :disabled="single" @click="handlePublish">发布</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="singList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="歌曲名称" align="center" prop="singName" />
      <el-table-column label="歌手名称" align="center" prop="singer" />
      <el-table-column label="律动一" align="center" prop="rhythmName1" />
      <el-table-column label="律动二" align="center" prop="rhythmName2" />
      <el-table-column label="默认曲调" align="center" prop="tune" />
      <el-table-column label="默认伴奏" align="center" prop="accompName" />
      <el-table-column label="节拍" align="center" prop="beat" />
      <el-table-column label="乐谱" align="center">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdateQupu(scope.row)"
            v-hasPermi="['system:sing:edit']">编辑曲谱</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUploadQupu(scope.row)"
            v-hasPermi="['system:sing:edit']">曲谱上传</el-button>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="releaseStatusName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sing:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:sing:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <MusicScore ref="musicScoreRef" @submit="getList" />
    <SheetUpload ref="sheetUploadRef" :song-name="selectItem.singName" :sing-id="selectItem.singId"
      @success="getList" />
    <!-- 添加或修改歌曲管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="singRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="歌曲名称" prop="singName">
          <el-input v-model="form.singName" placeholder="请输入歌曲名称" />
        </el-form-item>
        <el-form-item label="歌手名称" prop="singer">
          <el-input v-model="form.singer" placeholder="请输入歌手名称" />
        </el-form-item>
        <el-form-item label="节奏型一" prop="rhythm1">
          <el-select v-model="form.rhythm1" placeholder="请选择节奏型一">
            <el-option v-for="item in patternList1" :key="item.patternId" :label="item.patternName"
              :value="item.patternId" />
          </el-select>
        </el-form-item>
        <el-form-item label="节奏型二" prop="rhythm2">
          <el-select v-model="form.rhythm2" placeholder="请选择节奏型二">
            <el-option v-for="item in patternList2" :key="item.patternId" :label="item.patternName"
              :value="item.patternId" />
          </el-select>
        </el-form-item>
        <el-form-item label="曲调" prop="tune">
          <el-select v-model="form.tune" placeholder="请选择曲调">
            <el-option v-for="item in keys" :key="item" :label="item"
              :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="伴奏" prop="accompId">
          <el-select v-model="form.accompId" placeholder="请选择伴奏">
            <el-option v-for="item in accompList" :key="item.accompId" :label="item.accompName"
              :value="item.accompId" />
          </el-select>
        </el-form-item>
        <el-form-item label="节拍" prop="beat">
          <el-select v-model="form.beat" placeholder="请选择节拍">
            <el-option v-for="dict in beat" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sing">
import { ElMessage } from "element-plus";
import { listSing, getSing, delSing, addSing, updateSing } from "@/api/system/sing";
import { updateReleaseStatus, getSheet } from "@/api/system/sing";
import { listPattern } from "@/api/system/pattern";
import { listAccomp } from "@/api/system/accomp";
import { useDict } from "@/utils/dict";
import MusicScore from './MusicScore/index.vue';
import SheetUpload from '@/components/SheetUpload/index.vue';
import { computed } from "vue";

const { proxy } = getCurrentInstance();

const selectItem = ref({});
const singList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const musicScoreRef = ref(null);
const sheetUploadRef = ref(null);
const patternList = ref([]);
const accompList = ref([]);

// 节拍字典
const { beat } = useDict("beat");
const keys = ref(['G', 'Ab','A','Bb', 'B' ,'C', 'C#', 'D','D#', 'E', 'F', 'F#']);
const patternList1 = computed(() => {
  return patternList.value.filter(item => item.rhythm == '律动一');
});
const patternList2 = computed(() => {
  return patternList.value.filter(item => item.rhythm == '律动二');
})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    singName: null,
  },
  rules: {
  }
});

// 获取节奏型列表
function getPatternList() {
  listPattern({ pageSize: 1000 }).then(response => {
    patternList.value = response.rows;
  });
}

// 获取伴奏列表
function getAccompList() {
  listAccomp({ pageSize: 1000 }).then(response => {
    accompList.value = response.rows;
  });
}

const { queryParams, form, rules } = toRefs(data);

/** 查询歌曲管理列表 */
function getList() {
  loading.value = true;
  listSing(queryParams.value).then(response => {
    singList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 初始化时获取节奏型和伴奏列表
getPatternList();
getAccompList();

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("singRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.singId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加歌曲管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _singId = row.singId || ids.value
  getSing(_singId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改歌曲管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["singRef"].validate(valid => {
    if (valid) {
      if (form.value.singId != null) {
        updateSing(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSing(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _singIds = row.singId || ids.value;
  proxy.$modal.confirm('是否确认删除歌曲管理编号为"' + _singIds + '"的数据项？').then(function () {
    return delSing(_singIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 发布 */
async function handlePublish() {
  const _singIds = ids.value;
  const res = await updateReleaseStatus('published', _singIds[0])
  if (res.code == 200) {
    proxy.$modal.msgSuccess("发布成功");
    getList();
  }
}
/** 新增按钮操作 */
async function handleUpdateQupu(row) {
  let text = '{Intro:前奏}\n{Verse 歌词}\n{Interlude:间奏}\n{Verse 歌词}\n{Outro:尾奏}'
  if (row.sheetContext && row.sheetContext.length > 0) {
    text = row.sheetContext
  }
  if (musicScoreRef.value) {
    musicScoreRef.value.showDialog( row.singId, text );
  }
}
const handleUploadQupu = (row) => {
  selectItem.value = row;
  if (sheetUploadRef.value) {
    sheetUploadRef.value.showDialog();
  }
}
getList();
</script>
